package com.web.webstart.base.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.web.exiaodao.remote.vo.BannerVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.dozer.DozerBeanMapper;

/**
 * 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
 * 
 * 1. 持有Mapper的单例. 2. 返回值类型转换. 3. 批量转换Collection中的所有对象. 4.
 * 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
 *
 *  DozerBeanMapper对象之间相同属性名赋值 http://blog.csdn.net/luo201227/article/details/24021791
 *
 * @author calvin
 */
public class BeanMapper {

	/**
	 * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
	 */
	private static DozerBeanMapper dozer = new DozerBeanMapper();

	/**
	 * 基于Dozer转换对象的类型.
	 */
	public static <T> T map(Object source, Class<T> destinationClass) {
		return dozer.map(source, destinationClass);
	}

	/**
	 * 基于Dozer转换Collection中对象的类型.
	 */
	public static <T> List<T> mapList(
			@SuppressWarnings("rawtypes") Collection sourceList,
			Class<T> destinationClass) {
		List<T> destinationList = new ArrayList<T>();
		for (Object sourceObject : sourceList) {
			T destinationObject = dozer.map(sourceObject, destinationClass);
			destinationList.add(destinationObject);
		}
		return destinationList;
	}

	/**
	 * 基于Dozer将对象A的值拷贝到对象B中.
	 */
	public static void copy(Object source, Object destinationObject) {
		dozer.map(source, destinationObject);
	}

	public static void main(String[] args) throws Exception{
		BannerVo banner = new BannerVo();
		banner.setIntro("intro");
		banner.setType(1);
		banner.setObjectId(1111l);
        banner.setId(423423l);
        banner.setSort(11);
        banner.setPicurl("pic");
        banner.setLinkurl("linurl");
        banner.setCreateTime("time");
        banner.setCreateUser(null);
		System.out.println("aaaa:"+banner);

        BannerVo newB = new BannerVo();
		newB.setType(10);
        newB.setCreateUser("newB_User");
//		copy(banner, newB);
//		System.out.println("newB:"+newB);

        PropertyUtils.copyProperties(newB, banner);;
        System.out.println("newB:"+newB);

    }
}